// 15.三数之和

package LeetcodeHot100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution015 {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        for (int first = 0; first < nums.length; first++) {
            if (first >= 1 && nums[first] == nums[first - 1])
                continue;
            if (nums[first] > 0)
                continue;
            int second = first + 1, third = nums.length - 1;
            while (second < third) {
                if (nums[first] + nums[second] + nums[third] == 0) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    result.add(list);
                    while (second + 1 < nums.length && nums[second] == nums[second + 1])
                        second++;
                    second++;
                } else if (nums[first] + nums[second] + nums[third] > 0)
                    third--;
                else
                    second++;
            }
        }
        return result;
    }
}
